package com.umeox.watch.moto.chat.widget;


import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.text.style.UnderlineSpan;
import android.util.LayoutDirection;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.text.TextUtilsCompat;

import com.umeox.moto.common.constant.Features;
import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.DeviceManager;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;
import com.umeox.moto.watch.themes.util.ThemeUtils;
import com.umeox.moto.watch.themes.widget.ProgressView;
import com.umeox.watch.moto.chat.R;
import com.umeox.watch.moto.chat.db.ContactInfo;
import com.umeox.watch.moto.chat.ui.GroupSettingActivity;
import com.umeox.watch.moto.chat.utils.Recorder;
import com.umeox.watch.moto.dataservice.DataProvider;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class AlarmRecorderDialog extends Dialog implements View.OnClickListener, Recorder.OnRecorderListener {

    private Context mContext;
    private int mLayoutId;
    private GestureDetector mGestureDetector;
    public static final long MAX_DURATION = TimeUnit.SECONDS.toMillis(60);
    private int startY = 0;
    private Recorder mRecorder;
    private ValueAnimator increaseAnimator;
    private TextView mTimerTv;
    private View mRecordingVs;
    private boolean mBoolean;
    private PowerManager.WakeLock wakeLock;
    private LinearLayout mActionLl;
    private TextView mAction4;
    private ContactInfo mContactInfo;

    private boolean mOriginalRaiseUpOn;

    public AlarmRecorderDialog(@NonNull Context context, int layoutId, ContactInfo contactInfo) {
        super(context);

        mContext = context;
        mLayoutId = layoutId;
        mContactInfo = contactInfo;
        mOriginalRaiseUpOn = DeviceManager.getInstance().isRaiseUpOn();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(mLayoutId);
        wakeUpAndUnlock();
        final Button voiceButton = findViewById(R.id.tv_action_first);
        mActionLl = findViewById(R.id.ll_action);
        final TextView secondTv = findViewById(R.id.tv_action_second);
        final TextView action3 = findViewById(R.id.tv_action_3);
        final TextView action5 = findViewById(R.id.tv_action_5);
        final TextView tvQuite = findViewById(R.id.tvQuite);
        mAction4 = findViewById(R.id.tv_action_4);
        final String voiceTip = mContext.getString(R.string.voice_tip);
        final String format = String.format("%s\n%s", mContext.getText(R.string.voice), voiceTip);
        final int color = ThemeUtils.textColorTertiary(mContext, R.color.light_secondary_text_color);
        int pixelSize = 18;
        int index = format.indexOf(voiceTip);
        ColorStateList redColors = ColorStateList.valueOf(color);
        TextAppearanceSpan textAppearanceSpan = new TextAppearanceSpan("Gotham Rounded", 0, pixelSize, redColors, null);
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(format);
        spanBuilder.setSpan(textAppearanceSpan, index, index + voiceTip.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        voiceButton.setText(spanBuilder);

        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == LayoutDirection.RTL) {
            voiceButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, ResourceManager.getInstance().getDrawable(R.drawable.chat_voice), null);
        } else {
            voiceButton.setCompoundDrawablesRelativeWithIntrinsicBounds(ResourceManager.getInstance().getDrawable(R.drawable.chat_voice), null, null, null);
        }


        setDrawableStart(mAction4, R.drawable.ic_phrase);
        setDrawableStart(action3, R.drawable.chat_pic);
        setDrawableStart(secondTv, R.drawable.chat_emoji);
        setDrawableStart(action5, R.drawable.chat_setting);

        if (mContactInfo.getType() == 2) {
            String hiddenFeatures = DataProvider.getHiddenFeaturesByFriendId(mContactInfo.getFriendId());
            //voiceButton.setVisibility(hiddenFeatures(hiddenFeatures, Features.VOICE_CHAT) ? View.GONE : View.VISIBLE);
            secondTv.setVisibility(hiddenFeatures(hiddenFeatures, Features.BIG_EMOJI_CHAT) ? View.GONE : View.VISIBLE);
            mAction4.setVisibility(hiddenFeatures(hiddenFeatures, Features.TEXT_CHAT) ? View.GONE : View.VISIBLE);
//            action3.setVisibility(hiddenFeatures(hiddenFeatures, Features.TAKE_PHOTO_CHAT) ? View.GONE : View.VISIBLE);
        } else {
//            action3.setVisibility(View.VISIBLE);
        }


        mRecordingVs = findViewById(R.id.vs_recording);
        if (action3 != null) {
            action3.setOnClickListener(this);
        }
        if (mAction4 != null) {
            mAction4.setOnClickListener(this);
        }

        String text = tvQuite.getText().toString();
        // 创建 Spannable 对象
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new UnderlineSpan(), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvQuite.setText(spannableString);

        //只有设备群聊才有这个选项
        if (mContactInfo.isGroup() && mContactInfo.getType() == 2) {
            //管理员入口
            if (mContactInfo.isAdmin()) {
                action5.setVisibility(View.VISIBLE);
                action5.setOnClickListener(this);
                tvQuite.setVisibility(View.GONE);
                tvQuite.setOnClickListener(null);
            } else {
                action5.setVisibility(View.GONE);
                action5.setOnClickListener(null);
                tvQuite.setVisibility(View.VISIBLE);
                tvQuite.setOnClickListener(this);
            }

            if (DataProvider.getCustomGroup()) {
                if (mContactInfo.isAdmin()) {
                    action5.setVisibility(View.VISIBLE);
                    action5.setOnClickListener(this);
                    tvQuite.setVisibility(View.GONE);
                    tvQuite.setOnClickListener(null);
                } else {
                    action5.setVisibility(View.GONE);
                    action5.setOnClickListener(null);
                    tvQuite.setVisibility(View.VISIBLE);
                    tvQuite.setOnClickListener(this);
                }
            } else {
                action5.setVisibility(View.GONE);
                action5.setOnClickListener(null);
                tvQuite.setVisibility(View.GONE);
                tvQuite.setOnClickListener(null);
            }
        } else {
            action5.setVisibility(View.GONE);
            tvQuite.setVisibility(View.GONE);
            action5.setOnClickListener(null);
            tvQuite.setOnClickListener(null);
        }
        secondTv.setOnClickListener(this);

        mGestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public void onLongPress(MotionEvent e) {
                initRecordingLayout();
            }
        });

        voiceButton.setOnTouchListener(onTouchListener);

        mRecorder = Recorder.getInstance();
        mRecorder.seRecorderListener(this);

        final ProgressView recordCountdown = findViewById(R.id.pv_countdown);
        mTimerTv = findViewById(R.id.tv_timer);
        recordCountdown.setProgress(0);
        increaseAnimator = ValueAnimator.ofFloat(0, 1).setDuration(MAX_DURATION);
        increaseAnimator.setInterpolator(new LinearInterpolator());
        increaseAnimator.addUpdateListener(animation -> {
            float progress = (float) animation.getAnimatedValue();
            recordCountdown.setProgress(progress);
            if (progress >= 1 && mRecorder.isRunning()) {
                mRecorder.stop();
            }
        });

    }

    private boolean hiddenFeatures(String hiddenFeatures, String featuresStr) {
        if (TextUtils.isEmpty(hiddenFeatures)) {
            return false;
        }
        return hiddenFeatures.contains(featuresStr);
    }

    private void setDrawableStart(TextView actionTv, int p) {
        if (actionTv == null) {
            return;
        }
        if (TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == LayoutDirection.RTL) {
            actionTv.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, ResourceManager.getInstance().getDrawable(p), null);
        } else {
            actionTv.setCompoundDrawablesRelativeWithIntrinsicBounds(ResourceManager.getInstance().getDrawable(p), null, null, null);
        }
    }

    private void initRecordingLayout() {

        if (mActionLl != null) {
            mActionLl.removeView(mAction4);
        }
        mRecordingVs.setVisibility(View.VISIBLE);
        mRecorder.start((int) MAX_DURATION);
        increaseAnimator.start();
        if (mOriginalRaiseUpOn) {  //翻腕功能本身是开启的
            DeviceManager.getInstance().setRaiseUpValue(false);
        }


    }

    @Override
    public void dismiss() {
        super.dismiss();
        releaseLock();
        if (mOriginalRaiseUpOn) {
            DeviceManager.getInstance().setRaiseUpValue(true);
        }
    }

    final View.OnTouchListener onTouchListener = new View.OnTouchListener() {

        private int startY = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (mRecorder == null) {
                return false;
            }
            mGestureDetector.onTouchEvent(event);
            int action = event.getAction();
//            Log.d("zhanlv", "onTouch: " + action);
            final boolean running = mRecorder.isRunning();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int currentY = (int) event.getRawY();
                    int disY = currentY - startY;
                    if (disY < -40 && mRecorder.isRunning()) {
                        mRecorder.cancel();
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    if (running)
                        mRecorder.stop();
                    break;
            }
            return false;
        }
    };

    @SuppressLint("InvalidWakeLockTag")
    private void wakeUpAndUnlock() {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
                    | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Chat Recording");
        }

        wakeLock.acquire(MAX_DURATION);
    }

    private void releaseLock() {
        if (wakeLock != null) {

            try {
                wakeLock.release();
            } catch (Exception e) {
                Logger.e("Releasing wakelock failed:" + e);
            }
        } else {
            Logger.d("Wakelock reference is null");
        }
    }


    @Override
    public void onComplete(String filePath, long startMillis, long duration) {
        Logger.e("Chat", "duration=" + duration);
        increaseAnimator.cancel();
        if (mListener != null) {
            mListener.onVoice(filePath, duration);
        }

        dismiss();
    }

    @Override
    public void onUpdate(long duration) {
        mTimerTv.setText(TimeUnit.MILLISECONDS.toSeconds(MAX_DURATION - duration) + "''");
    }

    @Override
    public void onError(Exception e) {
        increaseAnimator.cancel();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.tv_action_3:
                mListener.onPhoto();
                dismiss();
                break;
            case R.id.tv_action_4:
                mListener.onPhrase();
                dismiss();
                break;
            case R.id.tv_action_5:
                GroupSettingActivity.Companion.intoGroupSettingActivity(mContext, mContactInfo);
                break;
            case R.id.tvQuite: {
                SunmitDialog dialog = new SunmitDialog(mContext);
                dialog.setListener(() -> {
                    dialog.dismiss();
                    mListener.onQuitGroup();
                });
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    dialog.create();
                }
                dialog.setTitle(mContext.getString(R.string.are_you_sure_you_want_to_exit_the_group));
                dialog.show();
            }
            break;

            case R.id.tv_action_second:
                mListener.onEmoji();
                dismiss();
                break;
        }
    }

    private OnDialogActionListener mListener;

    public void setListener(OnDialogActionListener listener) {
        mListener = listener;
    }

    public interface OnDialogActionListener {
        void onVoice(String filePath, long duration);

        void onEmoji();

        void onPhoto();

        void onPhrase();

        void onQuitGroup();

    }
}
